<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>


	
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Pagebakers » Using JSON in CakePHP 1.2</title>
		<meta name="generator" content="WordPress 2.1.2">
		<style type="text/css" media="screen">
			@import url( http://www.pagebakers.nl/wp-content/themes/pagebakersv2/style.css );
		</style>
		<script type="text/javascript" src="Pagebakers%20%C2%BB%20Using%20JSON%20in%20CakePHP%201.2_files/pngfix.js"></script>	
		<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://www.pagebakers.nl/feed/">
		<link rel="alternate" type="application/atom+xml" title="Atom 0.3" href="http://www.pagebakers.nl/feed/atom/">
		<link rel="shortcut icon" type="image/ico" href="http://www.pagebakers.nl/wp-content/themes/pagebakersv2/favicon.ico">
		<link rel="pingback" href="http://www.pagebakers.nl/xmlrpc.php">
		<meta name="verify-v1" content="sdTcNJBUoRnl7yOJqBbgVukSfy6Sj/FdoGAEM85eakk=">
	    	<link rel="archives" title="January 2008" href="http://www.pagebakers.nl/2008/01/">
	<link rel="archives" title="December 2007" href="http://www.pagebakers.nl/2007/12/">
	<link rel="archives" title="November 2007" href="http://www.pagebakers.nl/2007/11/">
	<link rel="archives" title="September 2007" href="http://www.pagebakers.nl/2007/09/">
	<link rel="archives" title="August 2007" href="http://www.pagebakers.nl/2007/08/">
	<link rel="archives" title="June 2007" href="http://www.pagebakers.nl/2007/06/">
	<link rel="archives" title="May 2007" href="http://www.pagebakers.nl/2007/05/">
	<link rel="archives" title="April 2007" href="http://www.pagebakers.nl/2007/04/">
	<link rel="archives" title="March 2007" href="http://www.pagebakers.nl/2007/03/">
	<link rel="archives" title="February 2007" href="http://www.pagebakers.nl/2007/02/">
	<link rel="archives" title="January 2007" href="http://www.pagebakers.nl/2007/01/">
	<link rel="archives" title="December 2006" href="http://www.pagebakers.nl/2006/12/">
	<link rel="archives" title="November 2006" href="http://www.pagebakers.nl/2006/11/">
	<link rel="archives" title="October 2006" href="http://www.pagebakers.nl/2006/10/">
	<link rel="archives" title="September 2006" href="http://www.pagebakers.nl/2006/09/">
	<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://www.pagebakers.nl/xmlrpc.php?rsd">
	</head><body>
		<div id="container">
			<div id="header">
				<h1 id="logo"><a href="http://www.pagebakers.nl/">Pagebakers</a></h1>
				
				<ul id="mainMenu">
					<li>
						<a href="http://www.pagebakers.nl/">Home</a>
					</li>
					<li>
						<a href="http://www.pagebakers.nl/archives" class="active">Archive</a>
					</li>
					<li>
						<a href="http://www.pagebakers.nl/about">About</a>
					</li>
				</ul>
				

				<div id="search">
					<div id="search_area">
						<form id="searchform" method="get" action="/index.php">
							<div>
							<input class="searchfield" name="s" id="s" value="" title="Enter keyword to search" type="text">
							</div>
						</form>
					</div>
				</div>
			</div>
			
			<div id="content">
<!-- end header -->	<div id="blog">
		<div class="inner">
			  
			<div id="post-50" class="post alt">
				<h2><a href="http://www.pagebakers.nl/2007/06/05/using-json-in-cakephp-12/" rel="bookmark">Using JSON in CakePHP 1.2</a></h2>	
				<span class="date">June 5th</span>

				<p class="tags"><img src="Pagebakers%20%C2%BB%20Using%20JSON%20in%20CakePHP%201.2_files/tag.gif" alt=""><a href="http://www.pagebakers.nl/category/documentation/" title="View all posts in Documentation" rel="category tag">Documentation</a>,  <a href="http://www.pagebakers.nl/category/development/" title="View all posts in Development" rel="category tag">Development</a>,  <a href="http://www.pagebakers.nl/category/ajax/" title="View all posts in Ajax" rel="category tag">Ajax</a>,  <a href="http://www.pagebakers.nl/category/tutorials/" title="View all posts in Tutorials" rel="category tag">Tutorials</a>,  <a href="http://www.pagebakers.nl/category/cakephp/" title="View all posts in CakePHP" rel="category tag">CakePHP</a>,  <a href="http://www.pagebakers.nl/category/javascript/" title="View all posts in Javascript" rel="category tag">Javascript</a>,  <a href="http://www.pagebakers.nl/category/json/" title="View all posts in JSON" rel="category tag">JSON</a></p>

				<div class="main">
					<p><strong>May
8th 2008 - Controller::$beforeFilter has been deprecated a while ago,
i’ve updated the example using Controller::beforeFilter()</strong></p>
<p>Almost an half year ago I created <a href="http://www.pagebakers.nl/2007/01/04/jsoncomponent-for-cakephp/">jsonComponent for CakePHP</a>, since then it has been used by quite a few people including myself. </p>
<p>About 3 months ago I started developing with CakePHP 1.2, one of the projects I’m working on is <a href="http://www.pagebakery.org/">Pagebakery</a>. Pagebakery relies heavily on AJAX and JSON and it’s therefore a perfect opportunity to experiment with CakePHP’s new features.</p>
<p>One of those features is <a href="http://api.cakephp.org/1.2/class_router.html#3e076ca36fc24418e193e967441395e3">Router::parseExtensions()</a>.
ParseExtensions allows you to parse the extension in your request and
let Cake select alternate layouts and views automatically.<br>
Another feature I found is JavascriptHelper::object(), this method is
also available in CakePHP 1.1 but I only stumbled on it recently. It’s
build-in JSON support in CakePHP, we no longer need the jsonComponent!</p>
<p>I’m going to explain you how to setup CakePHP 1.2 to output JSON
with help of Router::parseExtensions() and the
JavascriptHelper::object() method.<br>
<a id="more-50"></a></p>
<p>In this example we’re going to use a simple posts controller like the one in the Cake blog tutorial.</p>
<p>First we need to let Cake know to parse .json extentions. Add the following to /config/routes.php<br>
[source:php]<br>
Router::parseExtensions(’json’);<br>
[/source]</p>
<p>Because JSON is not a default content type in CakePHP currently, we
need to add it. We also need enable the RequestHandler component. Add
the following to your app_controller.php<br>
[source:php]<br>
var $components = array(’RequestHandler’);<br>
function beforeFilter() {<br>
	$this-&gt;RequestHandler-&gt;setContent(’json’, ‘text/x-json’);<br>
}<br>
[/source]<br>
Note: if you use beforeFilter in your controllers you need to call parent::beforeFilter()</p>
<p>Now we need to create our JSON layout.<br>
Create: /layouts/json/default.ctp<br>
Paste the following code in the new layout<br>
[source:php]<br>
&lt; ?php<br>
header("Pragma: no-cache");<br>
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");<br>
header('Content-Type: text/x-json');<br>
header("X-JSON: ".$content_for_layout);</p>
<p>echo $content_for_layout;<br>
?&gt;<br>
[/source]<br>
<em>Note: the X-JSON header is used by prototype.js and is automatically evaluated into a JSON object.</em></p>
<p>Next is our view, we’ll use the index action of the posts controller.<br>
Create: /views/posts/json/index.ctp<br>
And insert the following code in the view<br>
[source:php]<br>
&lt; ?php<br>
echo $javascript-&gt;object($aPosts);<br>
?&gt;<br>
[/source]<br>
<em>Note: the object method will convert the posts array into a json string, just like the jsonComponent.</em></p>
<p>Just to be clear here is the index action from the posts controller<br>
[source:php]<br>
function index() {<br>
	$this-&gt;set(’aPosts’, $this-&gt;Post-&gt;findAll());<br>
}<br>
[/source]</p>
<p>Now access your posts controller in your browser, <em>/posts/index/</em> will output the regular html view and <em>/posts/index.json</em> will output your json object!</p>
<p>Note that you can also use xml, rss (supported by default in CakePHP 1.2) to create your own feed in a snap! </p>
<p>Let me know if you have comments or additions.</p>
				</div>
				
				<div class="meta">
					<ul>
						<li><img src="Pagebakers%20%C2%BB%20Using%20JSON%20in%20CakePHP%201.2_files/link.png" alt="permalink icon"><a href="http://www.pagebakers.nl/2007/06/05/using-json-in-cakephp-12/">Permalink</a></li>
						<li><img src="Pagebakers%20%C2%BB%20Using%20JSON%20in%20CakePHP%201.2_files/trackback.png" alt="permalink icon"><a href="http://www.pagebakers.nl/2007/06/05/using-json-in-cakephp-12/trackback/">Trackback</a></li>
						<li><img src="Pagebakers%20%C2%BB%20Using%20JSON%20in%20CakePHP%201.2_files/comments.png" alt="permalink icon"></li>
					</ul>
				</div>
			</div>
			<!-- You can start editing here. -->
<div id="comments">
		<h3 class="reply">26 Responses to 'Using JSON in CakePHP 1.2'</h3> 
	<p class="comment_meta">Comments <a href="http://www.pagebakers.nl/2007/06/05/using-json-in-cakephp-12/feed/"><abbr title="Really Simple Syndication">RSS</abbr></a> 
			or <a href="http://www.pagebakers.nl/2007/06/05/using-json-in-cakephp-12/trackback/" rel="trackback">TrackBack</a> to 'Using JSON in CakePHP 1.2'.
		</p>
		<ol class="commentlist">

		
			<li class="alt" id="comment-4298">
				<h4 class="comment_author">
					<a href="http://www.vtek.nl/" rel="external nofollow">Ferdinant</a>				</h4>
				
				<p class="metadate">June 5th</p>
				
				
				<div class="commentText"><p>excellent post eelco! You go girl :)</p>
</div>

			</li>

		
		
			<li class="" id="comment-4326">
				<h4 class="comment_author">
					<a href="http://youmuppet.com/" rel="external nofollow">Dai Bach</a>				</h4>
				
				<p class="metadate">June 22nd</p>
				
				
				<div class="commentText"><p>Hi, great post, found it really useful.  Did run into a typo that caused me problems.</p>
<p>var $component = array(’RequestHandler’);   </p>
<p>should be</p>
<p>var $components = array(’RequestHandler’);</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4339">
				<h4 class="comment_author">
					<a href="http://www.pagebakers.nl/" rel="external nofollow">Eelco Wiersma</a>				</h4>
				
				<p class="metadate">June 24th</p>
				
				
				<div class="commentText"><p>Thanks for noticing Dai, glad to hear it’s useful!</p>
</div>

			</li>

		
		
			<li class="" id="comment-4365">
				<h4 class="comment_author">
					Raf				</h4>
				
				<p class="metadate">June 27th</p>
				
				
				<div class="commentText"><p>Any chance of you doing something similar in explaining how to parse a JSON string coming in as an input?</p>
<p>My client UI does an asynchronous post to the server to post data in
JSON. How do I go about getting that into my $data array sanitized
properly to use inside my controller and model safely?</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4368">
				<h4 class="comment_author">
					<a href="http://www.pagebakers.nl/" rel="external nofollow">Eelco Wiersma</a>				</h4>
				
				<p class="metadate">June 28th</p>
				
				
				<div class="commentText"><p>As far as I know the javascript helper only allows you to encode to JSON.</p>
<p>There are 2 options for you<br>
Use my <a href="http://www.pagebakers.nl/2007/01/04/jsoncomponent-for-cakephp/" rel="nofollow">JsonCompontent</a> to decode json.<br>
Or if you have PHP 5.2 you can use <a href="http://nl2.php.net/json_decode" rel="nofollow">json_decode</a></p>
<p>Good luck</p>
</div>

			</li>

		
		
			<li class="" id="comment-4400">
				<h4 class="comment_author">
					Melvin				</h4>
				
				<p class="metadate">July 9th</p>
				
				
				<div class="commentText"><p>Thanks ofr the tips Eelco</p>
<p>Just wondering, how do you pass a parameter to the URL when parseExtension is being used:<br>
e.g.</p>
<p>normally you would be able to do this</p>
<p><a href="http://localhost/products/list/1" rel="nofollow">http://localhost/products/list/1</a> </p>
<p>but if you want to return the data in json format, where do you place the category_id within the URL?</p>
<p><a href="http://localhost/products/list/1/data.json" rel="nofollow">http://localhost/products/list/1/data.json</a> doesn’t work for some reasons.</p>
<p>Thanks for your help in advance.</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4451">
				<h4 class="comment_author">
					<a href="http://www.pagebakers.nl/" rel="external nofollow">Eelco Wiersma</a>				</h4>
				
				<p class="metadate">July 18th</p>
				
				
				<div class="commentText"><p>Hi Melvin,</p>
<p>You got a good point there, I haven’t tested with that yet so I don’t have an answer for that yet.</p>
<p>My guess it would be:<br>
localhost/products/list/1.json</p>
<p>I’m currently on vacation but will have a look at it when I’m back home.</p>
<p>Please leave a comment if you find the solution.</p>
</div>

			</li>

		
		
			<li class="" id="comment-4521">
				<h4 class="comment_author">
					<a href="http://ahsanity.wordpress.com/2007/08/29/cakephp-12-the-romance-continues/" rel="external nofollow">CakePHP 1.2: The Romance Continues … « Ahsan’s Laboratory</a>				</h4>
				
				<p class="metadate">August 29th</p>
				
				
				<div class="commentText"><p>[…] Javascript Helper’s JSON object by Eelco Wiersma […]</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4548">
				<h4 class="comment_author">
					Abba Bryant				</h4>
				
				<p class="metadate">November 16th</p>
				
				
				<div class="commentText"><p>Just for confirmation.</p>
<p>the file extension should come after the last parameter.<br>
localhost/controller/action/param1/param2.js is correct.</p>
</div>

			</li>

		
		
			<li class="" id="comment-4576">
				<h4 class="comment_author">
					<a href="http://vacskamati.blogspot.com/" rel="external nofollow">Marton Sari</a>				</h4>
				
				<p class="metadate">January 31st</p>
				
				
				<div class="commentText"><p>Shouldn’t Content-Type be ‘application/json’ instead of ‘text/x-json’ ?</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4578">
				<h4 class="comment_author">
					impolite ben				</h4>
				
				<p class="metadate">February 1st</p>
				
				
				<div class="commentText"><p>how
could i forget to thank you first for this excellent post … you really
saved me a lot of headache and controller rewrites. have a great
weekend!</p>
</div>

			</li>

		
		
			<li class="" id="comment-4591">
				<h4 class="comment_author">
					Vince				</h4>
				
				<p class="metadate">February 22nd</p>
				
				
				<div class="commentText"><p>This is amazing!<br>
Thanks dude…</p>
<p>It’s now much much much easier to get what you looking for.</p>
<p>Thanks again. :)</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4592">
				<h4 class="comment_author">
					<a href="http://www.kiragame.com/" rel="external nofollow">kira gamer</a>				</h4>
				
				<p class="metadate">February 23rd</p>
				
				
				<div class="commentText"><p>thnaks a lot, i hope this code help me to change the content type of my rss when it’s cached !<br>
cakephp is a cool framework, but it lucks documentation :S soo much</p>
</div>

			</li>

		
		
			<li class="" id="comment-4597">
				<h4 class="comment_author">
					<a href="http://www.estetiks.com/" rel="external nofollow">estetik</a>				</h4>
				
				<p class="metadate">March 20th</p>
				
				
				<div class="commentText"><p>Very useful info for me. Thanx.</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4599">
				<h4 class="comment_author">
					snov				</h4>
				
				<p class="metadate">March 25th</p>
				
				
				<div class="commentText"><p>Nice and useful code n_n, this help me a lot, thanks.</p>
</div>

			</li>

		
		
			<li class="" id="comment-4604">
				<h4 class="comment_author">
					<a href="http://www.2a.com.tr/" rel="external nofollow">otogaz</a>				</h4>
				
				<p class="metadate">March 30th</p>
				
				
				<div class="commentText"><p>This is amazing!<br>
Thanks dude…</p>
<p>It’s now much much much easier to get what you looking for.</p>
<p>Thanks again. :</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4605">
				<h4 class="comment_author">
					peter				</h4>
				
				<p class="metadate">March 30th</p>
				
				
				<div class="commentText"><p>Hi, I can’t get it working following your steps.  It seems to choke on this line in the json/default.ctp file:</p>
<p>header(”X-JSON: “.$content_for_layout);</p>
<p>If I removed this line, then it seems to work.  Any idea why?</p>
</div>

			</li>

		
		
			<li class="" id="comment-4607">
				<h4 class="comment_author">
					<a href="http://www.kulak-estetigi.info/" rel="external nofollow">kulak estetigi</a>				</h4>
				
				<p class="metadate">April 2nd</p>
				
				
				<div class="commentText"><p>I’m
using a lot of CakePHP’s built in stuff to generate my HTML, and I’m
using jQuery to do some simple ajax stuff and some DOM manipulation. My
problem is, how to do my client/server interaction with JSON. I have
the facility in place for inline comments. When you see a paste, you
can double click on each line to create and view the comments. When you
create one, there is code that generates the comment and enters the
line number and paste ID.</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4608">
				<h4 class="comment_author">
					<a href="http://www.pagebakers.nl/" rel="external nofollow">Eelco Wiersma</a>				</h4>
				
				<p class="metadate">April 3rd</p>
				
				
				<div class="commentText"><p>@peter<br>
You probably have multiple lines in your view, check if there are any enters/spaces before or after &lt; ?php and  ?&gt;</p>
<p>@kulak<br>
You can send json to Cake with an ajax request, and decode it with my JsonComponent or json_encode(needs php5).<br>
I’m not exactly sure what you’re trying to do but maybe this helps :)</p>
</div>

			</li>

		
		
			<li class="" id="comment-4624">
				<h4 class="comment_author">
					Alfredo Herrejon				</h4>
				
				<p class="metadate">April 30th</p>
				
				
				<div class="commentText"><p>Hi, thanks its a good and an easy how to, I followed all your steps but I’am getting this error:</p>
<p>Dispatcher::start - Controller::$beforeFilter property usage is
deprecated and will no longer be supported. Use
Controller::beforeFilter(). [CORE/cake/dispatcher.php, line 298]</p>
<p>can somebody help me please? thanks</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4625">
				<h4 class="comment_author">
					Alfredo Herrejon				</h4>
				
				<p class="metadate">May 5th</p>
				
				
				<div class="commentText"><p>hi
everybody, thanks for this its very helpful, i am using it but i get an
error with the $beforeFilter, can somebody help me please, thanks. the
error is the following:</p>
<p> Dispatcher::start - Controller::$beforeFilter property usage is
deprecated and will no longer be supported. Use
Controller::beforeFilter(). CORE/cake/dispatcher.php, line 298</p>
</div>

			</li>

		
		
			<li class="" id="comment-4626">
				<h4 class="comment_author">
					steve smith				</h4>
				
				<p class="metadate">May 7th</p>
				
				
				<div class="commentText"><p>i
am working with cakephp, and i have the next question, i need to send
json data to cakephp to add a new record in the database, the question
is: how can i past the data to the function in my controller, and how
its supose i should handle, in $this-&gt;data or in $_POST, Thanks</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4627">
				<h4 class="comment_author">
					<a href="http://www.pagebakers.nl/" rel="external nofollow">Eelco Wiersma</a>				</h4>
				
				<p class="metadate">May 8th</p>
				
				
				<div class="commentText"><p>@Alfredo<br>
the piece of code in my example is outdated. You should use Controller::beforeFilter instead.</p>
<p>@Steve<br>
you could use $this-&gt;params[’form’]</p>
<p>Hope this helps</p>
</div>

			</li>

		
		
			<li class="" id="comment-4628">
				<h4 class="comment_author">
					CodeJunkie				</h4>
				
				<p class="metadate">May 9th</p>
				
				
				<div class="commentText"><p>I am also facing the same error as stated by Alfredo. Probably the new version of cakephp supports json now.</p>
<p>Please update us how to handle the Json part now and how to secure
the json result so that it can only be asked by application and not
viewed by just firing the url with extension json.</p>
<p>Thanks</p>
</div>

			</li>

		
		
			<li class="alt" id="comment-4629">
				<h4 class="comment_author">
					CodeJunkie				</h4>
				
				<p class="metadate">May 9th</p>
				
				
				<div class="commentText"><p>Another
thing that I want to accomplish is that I want to restrict few columns
in the table from json view. So how can we customize the object before
sending it for json encoding so that the table shows only particular
columns.</p>
</div>

			</li>

		
		
			<li class="" id="comment-4631">
				<h4 class="comment_author">
					Alfredo Herrejon				</h4>
				
				<p class="metadate">May 14th</p>
				
				
				<div class="commentText"><p>Hi,
thanks Eelco i actually get the json from my controller, i followed all
your steps, and it was working fine but now i have a problem, i don’t
know what i did but i now i can’t get the json, i am using jquery and
the request is with the status 0 with the loading in the response, the
problem is that, i have 22 records in the database, the funny here is
that if i add one record,(23 records) the json stay in loading, but if
i delete one record i get all the json, i have checked all, and it
appears to be fine, i don’t know what’s the problem. i apreciate your
help. thank you very much.</p>
</div>

			</li>

		
		
		</ol>

	 	
	<h3 class="reply" id="respond">Leave a comment</h3>

	
		<form action="http://www.pagebakers.nl/wp-comments-post.php" method="post" id="commentform">
			<div class="postinput">
			
				<p><input name="author" id="author" value="" size="22" tabindex="1" type="text">
				<label for="author"><small>Name (required)</small></label></p>

				<p><input name="email" id="email" value="" size="22" tabindex="2" type="text">
				<label for="email"><small>Mail (will not be published) (required)</small></label></p>

				<p><input name="url" id="url" value="" size="22" tabindex="3" type="text">
				<label for="url"><small>Website</small></label></p>
			
			
				<p class="allowedtags"><small><strong>XHTML:</strong>
You can use the following tags: &lt;a href="" title=""&gt; &lt;abbr
title=""&gt; &lt;acronym title=""&gt; &lt;b&gt; &lt;blockquote
cite=""&gt; &lt;code&gt; &lt;em&gt; &lt;i&gt; &lt;strike&gt;
&lt;strong&gt; <br>Please use the &lt;code&gt; tag when posting code, thanks.</small></p>

				<p><textarea name="comment" id="comment" cols="100" rows="10" tabindex="4"></textarea></p>

				<p><input name="submit" id="submit" tabindex="5" value="Submit Comment" title="Check your comment before posting it" type="submit">
				<input name="comment_post_ID" value="50" type="hidden">
				</p>
							</div>
		</form>

	


	</div>

			
					
					</div>
	</div>


<!-- begin sidebar -->
<div id="sidebar">
				<div id="categories">
		<h3>Flavours</h3>
		<ul>
			<br>
<b>Fatal error</b>:  Call to undefined function dynamic_sidebar() in <b>/home/pagebake/public_html/wp-content/themes/pagebakersv2/sidebar.php</b> on line <b>22</b><br>
</ul></div></div></div></div></body></html>